import os

import xlwt
from lxml import etree

from zc_getdata.config import Config
from zc_getdata.openurl import openurl


def saveList(l=[1], fname='test'):
    workbook = xlwt.Workbook(encoding="utf-8")
    worksheet = workbook.add_sheet("Sheet1")
    for i in range(len(l)):
        worksheet.write(i, 0, l[i])
    workbook.save(f'{fname}.xls')
    print(f'{fname} save success')


def zc_none_user(uid):
    bid = {}
    bid['uid'] = uid
    bid['Cumulative_turnover'] = 0
    bid['halfyear_turnover'] = 0
    bid['favorable_rate'] = 0
    bid['service_quality_rate'] = 0
    bid['membership_rank'] = 0
    bid['Employers_recommend'] = 0
    bid['enterprise_certification'] = False
    return bid


# 爬取bid信息
def get_UserInfo(bid_url) -> dict:
    fname = bid_url.split(r'/')[-1] + '.html'
    fpath = f'./data/bidHtml'
    PATH_SAVE_NAME = fpath + '/' + fname
    bid_page = ''

    if os.path.isfile(PATH_SAVE_NAME):
        parser = etree.HTMLParser(encoding='utf-8')
        bid_page = etree.parse(PATH_SAVE_NAME, parser=parser)
    else:
        if Config.blacklist.__contains__(fname):
            return zc_none_user(bid_url)
        else:
            bid_html = openurl(url=bid_url, savePath=fpath, saveName=fname)
        bid_page = etree.HTML(bid_html)
    bid = {}
    uid = bid_page.xpath('/html/body/div[2]/div/div[1]/div[2]/div/text()')
    if len(uid) == 0:
        return zc_none_user(bid_url)
    bid['bid_url'] = bid_url
    bid['uid'] = uid[0].strip().strip('智城识别ID ')
    bid['uname'] = ''
    bid['win'] = 0
    bid['projects_undertaken'] = bid_page.xpath('/html/body/div[2]/div/div[2]/div/div[1]/span[2]/text()')[0]
    rate = bid_page.xpath('/html/body/div[2]/div/div[2]/div/div[2]/span[2]/text()')[0]
    bid['favorable_rate'] = round(float(rate.strip('%')) / 100, 3)
    bid['level_of_membership'] = bid_page.xpath('/html/body/div[2]/div/div[2]/div/div[3]/a/span/text()')[
        0].strip().strip('级')
    general_income = bid_page.xpath('/html/body/div[2]/div/div[2]/div/div[4]/span[2]/text()')[0].strip()
    bid['general_income'] = general_income.strip('RMB').strip('￥').strip()
    # list
    skills = bid_page.xpath('//span[@class="tag"]/a/text()')
    bid['skills'] = ",".join(skills)
    services = bid_page.xpath('/html/body/div[2]/div/div[5]/span[@style ="color:black;"]/text()')
    bid['services'] = ",".join(services)
    area = bid_page.xpath('/html/body/div[2]/div/div[6]/span[@style ="color:black;"]/text()')
    bid['area'] = ",".join(area)
    return bid

# 保存单个项目的信息，同时爬取bid的信息并保存
def save_Single_Project(p={}, savePath=r'./data/zc_pInfo'):
    config = Config()
    fname = f"pinfo_{p['pid']}"
    workbook = xlwt.Workbook(encoding="utf-8")
    worksheet = workbook.add_sheet("project_sheet")
    kset = list(p.keys())
    # 第一列 字段名
    for i in range(len(config.project_fields)):
        worksheet.write(i, 0, config.project_fields[i])

    bids = list(p['bids'])
    for i in range(len(kset)):
        k = kset[i]
        v = p[k]
        if (isinstance(v, set)):
            for j in range(len(bids)):
                worksheet.write(i, 1 + j, bids[j][0])
                worksheet.write(i + 1, 1 + j, bids[j][1])
        else:
            worksheet.write(i, 1, p[k])
    # 爬取并保存bids的信息
    bids_worksheet = workbook.add_sheet("bids_sheet")
    contractor_name = p['contractor_name']

    # 第一行 字段名
    for i in range(len(config.bid_fields)):
        bids_worksheet.write(0, i, config.bid_fields[i])
    for i in range(len(bids)):
        bid_url = bids[i][1]
        uname = bids[i][0]
        bid = get_UserInfo(bid_url)
        bid['uname'] = uname
        # 标记是否成功
        if (uname == contractor_name):
            bid['win'] = 1
        for j in range(len(config.bid_fields)):
            field = config.bid_fields[j]
            value = bid[field]
            bids_worksheet.write(i + 1, config.bid_index[field], value)
    workbook.save(f'{savePath}/{fname}.xls')
    print(f'{fname} save success')
